// Copyright 2008 web2me.dev
//
//   Licensed under the Apache License, Version 2.0 (the "License");
//   you may not use this file except in compliance with the License.
//   You may obtain a copy of the License at
//
//       http://www.apache.org/licenses/LICENSE-2.0
//
//   Unless required by applicable law or agreed to in writing, software
//   distributed under the License is distributed on an "AS IS" BASIS,
//   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//   See the License for the specific language governing permissions and
//   limitations under the License.

package net.web2me.gui;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JPanel;
import javax.swing.JTextField;

import net.web2me.api.ParserExecutor;

import org.apache.log4j.Logger;

public class StartButtonActionListener implements ActionListener, GuiParserExecutorWrapperListener {
	
	private static final int CLICK_TO_START = 0;
	
	private static final int CLICK_TO_ABORT = 1;

	private Logger logger = Logger.getLogger(StartButtonActionListener.class);

	private JPanel context;
	
	private JButton startButton;

	private int currentState = CLICK_TO_START;
	
	private GuiParserExecutorWrapper executorWrapper;

	public StartButtonActionListener(JPanel context) {
		this.context = context;
	}

	public void actionPerformed(ActionEvent e) {
		if(currentState == CLICK_TO_ABORT) {
			logger.info("Aborting execution");
			
			executorWrapper.abort();
			startButton.setText(GuiConstants.START_BUTTON_START_TEXT);
			currentState = CLICK_TO_START;
			
			return;
		}
		
		logger.info("Starting execution");
		
		startButton = (JButton) context
		.getComponent(Web2MeGuiSwing.START_BUTTON);
		
		JTextField urlField = (JTextField) context
				.getComponent(Web2MeGuiSwing.URL_FIELD);
		JTextField dirField = (JTextField) context
				.getComponent(Web2MeGuiSwing.DIR_FIELD);
		JComboBox parsersCombo = (JComboBox) context
				.getComponent(Web2MeGuiSwing.PARSER_COMBO);
		JCheckBox historyCheck = (JCheckBox) context
		.getComponent(Web2MeGuiSwing.HISTORY_CHECK);
		JCheckBox metadataCheck = (JCheckBox) context
		.getComponent(Web2MeGuiSwing.METADATA_CHECK);

		final ParserExecutor executor = new ParserExecutor(
				parsersCombo.getSelectedItem().toString(), 
				dirField.getText(), 
				urlField.getText(), 
				historyCheck.isSelected(),
				metadataCheck.isSelected());
		
		
		executorWrapper = new GuiParserExecutorWrapper(context, executor, this);
		executorWrapper.execute();
		
		startButton.setText(GuiConstants.START_BUTTON_ABORT_TEXT);
		currentState = CLICK_TO_ABORT;
	}

	public void onParserFinished() {
		startButton.setText(GuiConstants.START_BUTTON_START_TEXT);
		currentState = CLICK_TO_START;
	}

}
